package com.yutian.example.demo.forum.service;

import com.yutian.example.demo.common.vo.PageData;
import com.yutian.example.demo.forum.dao.TopicDAO;
import com.yutian.example.demo.forum.dao.model.Topic;
import com.yutian.example.demo.forum.dao.model.req.TopicPageReqDO;
import com.yutian.example.demo.forum.dao.model.rsp.TopicPageRspDO;
import com.yutian.example.demo.service.forum.IForumService;
import com.yutian.example.demo.service.forum.param.req.ForumListTopicReq;
import com.yutian.example.demo.service.forum.param.req.ForumPageTopicReq;
import com.yutian.example.demo.service.forum.param.rsp.ForumListTopicRsp;
import com.yutian.example.demo.service.forum.param.rsp.ForumPageTopicRsp;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("forumService")
public class ForumServiceImpl implements IForumService {
    @Autowired
    private TopicDAO topicDAO;

    public List<ForumListTopicRsp> listTopic(ForumListTopicReq req) {
        List<Topic> topics = topicDAO.list(req.getTitleLike());
        return topics.stream().map(it -> {
            ForumListTopicRsp item = new ForumListTopicRsp();
            BeanUtils.copyProperties(it, item);
            return item;
        }).collect(Collectors.toList());
    }

    @Override
    public PageData<ForumPageTopicRsp> pageTopic(ForumPageTopicReq forumPageTopicReq) {
        TopicPageReqDO req = TopicPageReqDO.of(forumPageTopicReq);
        BeanUtils.copyProperties(forumPageTopicReq, req);

        long total = topicDAO.count(req);
        List<TopicPageRspDO> topics = topicDAO.page(req);

        List<ForumPageTopicRsp> rows = topics.stream().map(it -> {
            ForumPageTopicRsp row = new ForumPageTopicRsp();
            row.setId(it.getId());
            row.setTitle(it.getTitle());
            // mock
            row.setImportance(null == forumPageTopicReq.getImportance() ? 1 : forumPageTopicReq.getImportance());
            row.setType(StringUtils.isBlank(forumPageTopicReq.getType()) ? "CN" : forumPageTopicReq.getType());
            return row;
        }).collect(Collectors.toList());

        PageData<ForumPageTopicRsp> res = new PageData<ForumPageTopicRsp>(rows, forumPageTopicReq.getPage(), total);
        return res;
    }


}